function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++)
    {
        var c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}
function setCookie(cname,cvalue,domain = window.location.host,exdays = 1)
{
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + "domain=" + domain + "; " + expires; //cookie 的名称为 cname，cookie 的值为 cvalue，并设置了 cookie 的过期时间 expires。
}
function createHeader()
{
    let token = getCookie('vue_admin_huocms_token');
    return {
        'Authorization': 'Bearer ' + token
    }
}

function request(url, method, data) {
    let result = {};
    $.ajax({
        type: method,
        url: url,
        headers: createHeader(),
        data: data,
        async: false,
        dataType: "json",
        success: function(res){
            // console.log(res, '接口返回');
            if (res.code && res.code != 0) {
                alert(res.msg)
                // window.location.href = '/admin.php'
            }
            result = res
        }
    });
    return result
}

function checkUser()
{
    let site_id = getCookie('webSiteId')
    let token = getCookie('vue_admin_huocms_token');
    if (!token) {
        window.location.href = '/admin.php'
        return ;
    }
    let res = request('/websiteLang/index', 'GET', {site_id: site_id})
    if (!res.data) {
        window.location.href = '/admin.php'
    }
}
function getHtml(htmlPath) {
    return request('/design/getDesignHtml', 'GET', {html_path: htmlPath})
}
function getNavList() {
    let site_id = getCookie('webSiteId')
    let lang = getCookie('lang')
    let res = request('/navCate/index', 'GET', {website_id: site_id, lang: lang})
    return res.data
}
function getNavData(navCateId) {
    let site_id = getCookie('webSiteId')
    let lang = getCookie('lang')
    let res = request('/nav/index', 'GET', {website_id: site_id, lang: lang, cate_id: navCateId})
    return res.data
}
function getBannerList() {
    let res = request('/slideCate/index', 'GET', {})
    return res.data
}
function getBannerData(slide_cate_id) {
    let res = request('/slide/index', 'GET', {slide_cate_id: slide_cate_id})
    return res.data
}
function getCategoryList(type = "suq_block1") {
    let site_id = getCookie('webSiteId')
    let lang = getCookie('lang')
    let res = request('/design/getCategoryList', 'GET', {website_id: site_id, lang: lang, type: type})
    return res.data
}
function getBlockData(category_id, type = "suq_block1") {
    let res = request('/design/getCategoryData', 'GET', {category_id: category_id, type : type})
    return res.data
}
// 打开当前文件的历史版本
$('#history-btn').on('click', function () {
    let nowFile = Vvveb.FileManager.getCurrentFile();

    if (nowFile && !$('#historyList').hasClass('open')) {

        $('#historyList').addClass('open')

        // if (!$('#vvveb-builder').hasClass('no-right-panel')) {
        //     $('#toggle-right-column-btn').click()
        // }

        $('#historyList ul li').remove();

        let site_id = getCookie('webSiteId')
        let lang = getCookie('lang')

        let param = {
            init_page: nowFile,
        }

        param["website_id"] = site_id
        param["lang"] = lang

        let headers = createHeader()

        loading('history-btn', '', '')

        $.ajax({
            type: "GET",
            url: '/design/history',//set your server side save script url
            data: param,
            headers: headers,
            cache: false,
            success: function (res) {

                // console.log(res, 'history>>>>>>>>>>>>>');
                if (res.code == 0) {
                    var html = '';
                    for (const item of res.data) {
                        html += '<li data-page="'+ item.file +'?preview=1" data-version="'+item.version+'">\n' +
                            '      <div class="infoBox">\n' +
                            '       页面：index (版本：<i class="version">'+item.version+'</i>)<br/>\n' +
                            '       时间：'+item.create_time+' <br/>\n' +
                            '       作者：'+item.admin_name+'\n' +
                            '      </div>\n' +
                            '      <div class="btnBox" >\n' +
                            '       <span class="preview">查看</span>\n' +
                            '      </div>\n' +
                            '     </li>';
                    }
                    $('#historyList ul').append(html)
                }

                removeLoading('history-btn')
            },
            error: function (res) {
                alert(res.responseText);
                removeLoading('history-btn')
            }
        });
    }
    else {
        $('#historyList').removeClass('open')
    }
});

$('.closeHistoryBox').on('click', function () {
    $('#historyList').removeClass('open')
});

$('#historyList ul').on('click', 'li .btnBox', function () {
    console.log('按钮点击')

    let nowFile = Vvveb.FileManager.getCurrentFile();
    let site_id = getCookie('webSiteId')
    let lang = getCookie('lang')

    let param = {
        init_page: nowFile,
        version: $(this.parentNode).data("version"),
    }

    param["website_id"] = site_id
    param["lang"] = lang

    let headers = createHeader()
    let that = $(this)

    let page = $(this.parentNode).data("page");
    console.log($(this.parentNode), '$(this.parentNode)>>>>>>>>>')

    loading('history-view', '', '')

    $.ajax({
        type: "POST",
        url: '/design/setPreviewPage',//set your server side save script url
        data: param,
        headers: headers,
        cache: false,
        success: function (res) {

            console.log(res, 'history-view>>>>>>>>>>>>>');
            let url;
            if (res.code == 0) {
                url = '/' + page
                Vvveb.Builder.loadUrl(url + ((url.indexOf('?') > -1 ? '&r=' : '?r=') + Math.random()),
                    function () {
                        Vvveb.FileManager.loadComponents(false);
                        Vvveb.SectionList.loadSections(false);
                        Vvveb.StyleManager.init();
                    });

                $('#historyList ul li.active').removeClass('active')
                that.parents('#historyList ul li').addClass('active')
            }

            removeLoading('history-view')
        },
        error: function (res) {
            alert(res.responseText);
            removeLoading('history-view')
        }
    });
})



